package tk.djcrazy.tuguaconverter;

import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.UnsupportedEncodingException;
import java.net.URLEncoder;
import java.util.ArrayList;
import java.util.List;
import java.util.concurrent.CountDownLatch;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

import org.apache.commons.logging.Log;
import org.apache.http.HttpEntity;
import org.apache.http.HttpResponse;
import org.apache.http.HttpStatus;
import org.apache.http.NameValuePair;
import org.apache.http.client.ClientProtocolException;
import org.apache.http.client.HttpClient;
import org.apache.http.client.entity.UrlEncodedFormEntity;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.conn.ClientConnectionManager;
import org.apache.http.cookie.Cookie;
import org.apache.http.entity.mime.MultipartEntity;
import org.apache.http.entity.mime.content.FileBody;
import org.apache.http.entity.mime.content.StringBody;
import org.apache.http.impl.client.DefaultHttpClient;
import org.apache.http.message.BasicNameValuePair;
import org.apache.http.protocol.HTTP;
import org.apache.http.util.EntityUtils;

public class HttpGetHtml {
	private static DefaultHttpClient client_tugua = new DefaultHttpClient();
	private static DefaultHttpClient client = new DefaultHttpClient();
	private static final String CC98 = "http://10.10.98.98/";
	private static int Count = 1;

	/**
	 * 
	 * @param url
	 * @return
	 * @throws UnsupportedEncodingException
	 */
	public static String getHtml(String url)
			throws UnsupportedEncodingException {
		System.out.println("正在获取网页内容...");
		String content = "";
		try {
			HttpGet get = new HttpGet(url);
			HttpResponse response = client_tugua.execute(get);
			HttpEntity entity = response.getEntity();
			if (entity != null) {
				content = EntityUtils.toString(entity);
			}
			if (entity != null)
				entity.consumeContent();
		} catch (Exception e) {
			// TODO: handle exception
			System.out.println("网络连接失败！");
		}
		byte[] bs = content.getBytes("ISO-8859-1");
		String str = new String(bs, "GBK");

		return new String(str.getBytes("UTF-8"), "UTF-8");

	}

	/**
	 * 
	 * @param url
	 * @return
	 */
	public static boolean DownloadPicture(String url) {
		// 设置需要下载的文件
		HttpGet httpGet = new HttpGet(url);
		System.out.println("正在下载第" + Count + "张图片...");
		try {
			HttpResponse response = client_tugua.execute(httpGet);

			if (HttpStatus.SC_OK == response.getStatusLine().getStatusCode()) {
				HttpEntity entity = response.getEntity();
				// 显示内容
				if (entity != null) {

					// 设置本地保存的文件
					File storeFile = new File("D:\\aaaaaa.jpg");
					FileOutputStream output = new FileOutputStream(storeFile);
					// 得到网络资源并写入文件
					InputStream input = entity.getContent();
					byte b[] = new byte[1024];
					int j = 0;
					while ((j = input.read(b)) != -1) {
						output.write(b, 0, j);
					}
					output.flush();
					output.close();
					if (entity != null)
						entity.consumeContent();
					Count++;
				}
			}
		} catch (IOException e) {
			// TODO: handle exception
			System.out.println("下载图片失败：" + url);
			return false;
		}
		return true;
	}

	/**
	 * 
	 * @return
	 */
	@SuppressWarnings("deprecation")
	public static String UploadPictureToCC98() {
		String filePath = "D:\\aaaaaa.jpg";
		String replyContent = "";
		// 请求处理页面
		HttpPost httppost = new HttpPost(CC98
				+ "saveannouce_upfile.asp?boardid=10");
		System.out.println("正在上传第" + Count + "张图片到CC98...");
		try {
			// 创建待处理的文件
			FileBody file = new FileBody(new File(filePath));
			// 创建待处理的表单域内容文本
			StringBody descript = new StringBody("0431.la");

			// 对请求的表单域进行填充
			MultipartEntity reqEntity = new MultipartEntity();
			reqEntity.addPart("file", file);
			reqEntity.addPart("descript", descript);
			// 设置请求
			httppost.setEntity(reqEntity);
			// 执行
			HttpResponse response = client.execute(httppost);
			HttpEntity entity = response.getEntity();
			// 显示内容
			if (entity != null) {
				replyContent = EntityUtils.toString(entity);
				entity.consumeContent();
			}

		} catch (IOException e) {
			// TODO: handle exception
			return null;
		}
		String picUrl = "";
		String regex = "http://file.cc98.org/uploadfile/.*?jpg";
		Pattern pattern = Pattern.compile(regex, Pattern.DOTALL);
		Matcher matcher = pattern.matcher(replyContent);
		if (matcher.find()) {
			picUrl = matcher.group();
			return picUrl;
		} else {
			return null;
		}
	}

	/**
	 * 
	 * @param id
	 * @param pw
	 * @return
	 */
	public static boolean LoginCC98(String id, String pw) {
		HttpResponse response;
		boolean flag = false;
		List<Cookie> cookies;
		try {
			HttpPost httpost = new HttpPost(CC98 + "login.asp?action=chk");
			List<NameValuePair> nvps = new ArrayList<NameValuePair>();
			nvps.add(new BasicNameValuePair("username", id));
			nvps.add(new BasicNameValuePair("password", pw));
			nvps.add(new BasicNameValuePair("CookieDate", "3"));
			nvps.add(new BasicNameValuePair("loginaction", "login"));
			nvps.add(new BasicNameValuePair("userhidden", "2"));
			httpost.setEntity(new UrlEncodedFormEntity(nvps, HTTP.UTF_8));
			response = client.execute(httpost);

			cookies = client.getCookieStore().getCookies();
			if (cookies.toString().contains(URLEncoder.encode(id, "utf-8"))) {
				flag = true;
				System.out.println("登录CC98成功，准备上传图片...");

			}
			httpost.abort();

		} catch (ClientProtocolException e) {
			// TODO: handle exception
		} catch (UnsupportedEncodingException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		} catch (IOException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
		return flag;
	}
}
